/****************************************************************************
Copyright (c) 2011-2013,WebJet Business Division,CYOU

http://www.genesis-3d.com.cn

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/

using System;
using ScriptRuntime;

namespace ScriptRuntime
{


    public class ThirdPerson : ScriptableClass
    {
		enum MoveState
		{
			None = 0,
			Forward = 1 << 0,
			Backward = 1 << 1,
			Left = 1 << 2,
			Right = 1 << 3,
			ForwardLeft = Forward | Left,
			ForwardRight = Forward | Right,
			BackwardLeft = Backward | Left,
			BackwardRight = Backward | Right,
		}
		
		enum CharacterState
		{
			Idle = 0,
			Run,
			Jump
		}


        protected float mSpeed = -100f;
        protected float mRotationSpeed = 4.0f;
		protected float mMouseRotationSpeed = 8.0f;
        protected Vector2 mScreenPostion = new Vector2(0.0f, 0.0f);
        protected float mMouseY = 0.0f;
        protected float mMouseX = 0.0f;
		protected Matrix44 mWorld;
		protected PhysicsBodyComponent CCC;

		protected float fakeGravity = -2.0f;
		protected float initialjumpSpeed = 30.0f;
		protected bool isOnGround = true ;
		protected float groundHeight = 0.0f;
		protected AssetPath idleAniPath = new AssetPath("asset:FengXiaoSu1/pose.anim",ResType.Animation);
		protected AssetPath runAniPath = new AssetPath("asset:FengXiaoSu1/run1.anim",ResType.Animation);
		protected AssetPath jumpAniPath = new AssetPath("asset:FengXiaoSu1/jump.anim",ResType.Animation);
		
		private Vector3 moveDir = new Vector3(0.0f,0.0f,0.0f);
		private Vector3 movePoint = new Vector3(0.0f,0.0f,0.0f);
		private float jumpSpeed = 30.0f;
		private CharacterState characterstate = CharacterState.Idle;
		private CharacterState lastCharacterstate;
		
		public override void OnLoad()
        {
			CCC = Owner.GetComponent<PhysicsBodyComponent>();
			//idleAniPath.assetPath = @"asset:FengXiaoSu1/pose.anim";
			//runAniPath.assetPath =  @"asset:FengXiaoSu1/run1.anim";
			//jumpAniPath.assetPath = @"asset:FengXiaoSu1/jump.anim";
			mWorld = Owner.WorldTransform;
		}

		public override void OnBeginFrame ()
		{
			if (CCC == null ) 
			{
				return;
			}

			movePoint = new Vector3 (0.0f, 0.0f, 0.0f);
			OnGround();
			ApplyGravity ();
			bool move = moveControl ();
			bool mouseRotate = MouseRotationControl ();
			if (move) 
			{
				if (mouseRotate) 
				{
					normalizeRolation ();
				}
				moveDir.Normalize ();
				movePoint = moveDir * (mSpeed * Util.GetDeltaTime ());
				CCC.MovePosition (ref movePoint);

			} 
			if (mouseRotate) 
			{
				normalizeRolation();
			}
			CharacterStateControl();
			lastCharacterstate = characterstate;
		}

		public override void OnFrame()
        {
        }
		
		protected bool moveControl()
        {
            bool ret = false;
			MoveState movestate = MoveState.None;
			//moving
			if (Input.KeyPressed (Code.W)) 
			{
				movestate |= MoveState.Forward;
				characterstate = CharacterState.Run;
			} 
			else if (Input.KeyPressed (Code.S)) 
			{
				movestate |= MoveState.Backward;
				characterstate = CharacterState.Run;
			} 
			else if (Input.KeyDown (Code.Space)) 
			{

				characterstate = CharacterState.Jump;
				DoJump();
			} 
			else 
			{
				if (characterstate != CharacterState.Jump) 
				{
					characterstate = CharacterState.Idle;
				}

			}

			//Rotation
			if (Input.KeyPressed (Code.A)) 
			{
				Matrix44 up = Matrix44.CreateRotationY(mRotationSpeed * Util.GetDeltaTime());
				Quaternion rotation = Quaternion.CreateFromRotationMatrix(up);
				CCC.RotationRotation(ref rotation);
			} 
			else if (Input.KeyPressed (Code.D)) 
			{
				Matrix44 up = Matrix44.CreateRotationY( mRotationSpeed * -Util.GetDeltaTime() );
				Quaternion rotation = Quaternion.CreateFromRotationMatrix(up);
				CCC.RotationRotation(ref rotation);
			}


			switch (movestate)
            {
                case MoveState.Forward:
                    {
						moveDir = Owner.LocalTransform.Forward;
						ret = true;
                    }
                    break;
                case MoveState.Backward:
                    {
						moveDir = Owner.LocalTransform.Backward;
						ret = true;
                    }
                    break;
                case MoveState.Left:
                    {
						moveDir = Owner.LocalTransform.Left;
						ret = true;
                    }
                    break;
                case MoveState.Right:
                    {
						moveDir = Owner.LocalTransform.Right;
						ret = true;
                    }
                    break;
                case MoveState.ForwardLeft:
                    {
						moveDir = Owner.LocalTransform.Forward + Owner.LocalTransform.Left;
						ret = true;
                    }
                    break;
                case MoveState.ForwardRight:
                    {
						moveDir = Owner.LocalTransform.Forward + Owner.LocalTransform.Right;
						ret = true;
                    }
                    break;
                case MoveState.BackwardLeft:
                    {
						moveDir = Owner.LocalTransform.Backward + Owner.LocalTransform.Left;   
						ret = true;
                    }
                    break;
                case MoveState.BackwardRight:
                    {
						moveDir = Owner.LocalTransform.Backward + Owner.LocalTransform.Right;   
						ret = true;
                    }
                    break;
                default:
                    {
                        ret |= false;
                    }
                    break;
            }
            return ret;
        }

        protected bool MouseRotationControl()
        {
            if (Input.MouseButtonDown(MouseCode.RightButton))
            {
                Input.GetScreenPosition(out mScreenPostion);
            }
            else if (Input.MouseButtonPressed(MouseCode.RightButton))
            {
                Vector2 temp;
                Input.GetScreenPosition(out temp);
                Vector2 bias = temp - mScreenPostion;
                mScreenPostion = temp;
                if (bias.X != 0.0f || bias.Y != 0.0f)
                {
                    Matrix44 up = Matrix44.CreateRotationY(-bias.X * mRotationSpeed);
					Quaternion rotation = Quaternion.CreateFromRotationMatrix(up);
					CCC.RotationRotation(ref rotation);
					return true;
                }
            }
            return false;
        }

        protected void normalizeRolation()
        {
            Vector3 right = mWorld.Right;
            right.Y = 0.0f;
            right.Normalize();

            Vector3 back = Vector3.Cross(right, mWorld.Up);
            Vector3 up = Vector3.Cross(back, right);
            mWorld.Right = right;
            mWorld.Backward = back;
            mWorld.Up = up;
        }



		protected void OnGround ()
		{
			if (CCC.IsOnGround) 
			{

				isOnGround = true;
				if (lastCharacterstate == CharacterState.Jump) 
				{
					characterstate = CharacterState.Idle;
					jumpSpeed = 0.0f;
				}

			} 
		}

		protected void DoJump ()
		{
			Vector3 jumpDir = Owner.LocalTransform.Up;
			jumpSpeed = initialjumpSpeed;
			Vector3 jumpMove = jumpDir * jumpSpeed *Util.GetDeltaTime();
			CCC.MovePosition(ref jumpMove);


		}

		protected void ApplyGravity ()
		{
			Vector3 jumpDir = Owner.LocalTransform.Up;
			if (!CCC.IsOnGround) 
			{
				jumpSpeed += fakeGravity;
				Vector3 jumpMove = jumpDir * jumpSpeed *Util.GetDeltaTime();
				CCC.MovePosition(ref jumpMove);
			}

		}



		protected void CharacterStateControl ()
		{
			switch (characterstate) 
			{
			case CharacterState.Idle:
				{
					Owner.Animation.CrossFading (idleAniPath.assetPath);
					break;
				}
			case CharacterState.Run:
				{
					Owner.Animation.CrossFading (runAniPath.assetPath);
					break;
				}
			case CharacterState.Jump:
				{
					Owner.Animation.CrossFading(jumpAniPath.assetPath);
					break;
				}
			}
		}
    }
}